package Chapter06;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 使用重入锁实现线程同步
 * Lock对象和synchronized关键字的选择
 * 最好两个都别用,使用一种java.util.concurrent包提供的机制,能够帮助用户处理
 * 所有与锁有关的代码。如果synchronized关键字都能满足用户的需求,就用它,因为能
 * 简化代码。如果需要更高级的功能,使用Lock对象,在使用ReentrantLock()类时，要
 * 注意及时释放锁,否则程序会出现死锁,通常将其放在finally代码块中释放。
 * Created by a on 2017/6/12.
 */
public class Test136 {
    public static void main(String[] args) {

        Bank2 bank2 = new Bank2();
        Transfer2 transfer2 = new Transfer2(bank2);
        Thread thread = new Thread(transfer2);
        Thread thread1 = new Thread(transfer2);
        thread.start();
        thread1.start();
    }
}

class Bank2 {
    private int account = 100;
    private Lock lock = new ReentrantLock();
    public void deposit(int money){
        lock.lock();
        try {
            account += money;
        }finally {
            lock.unlock();
        }
    }

    public int getAccount(){
        return account;
    }
}

class Transfer2 implements Runnable
{
    private Bank2 bank;

    public Transfer2(Bank2 bank) {
        this.bank = bank;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10;i++){
            bank.deposit(10);
            System.out.println("账户余额为:"+bank.getAccount());
        }
    }
}
